package com.code.statistics.managers;

import com.alibaba.fastjson.JSON;
import com.code.statistics.models.bo.TokenSwapManageResponse;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * http调用的相关管理类
 *
 * @author xiaoyaowang
 */
@Component
@Slf4j
public class HttpManager {

    @Value("${tokenSwap.manageUrlCheckToken}")
    private String tokenSwapManageCheckTokenUrl;

    @Autowired
    private RestTemplate restTemplate;

    private static final String ACCEPT = "Accept";

    /**
     * 验证token
     *
     * @param token 登录token
     * @return 验证与否
     */
    public Boolean verifyToken(String token) {
        //设置请求参数
        Map<String, Object> postData = Maps.newHashMapWithExpectedSize(1 << 4);
        postData.put("token", token);
        String requestBody = JSON.toJSONString(postData);
        log.info("请求体数据：【{}】", requestBody);
        HttpEntity<String> formEntity = new HttpEntity<>(requestBody, getJsonHeader());
        HttpMethod method = HttpMethod.POST;
        ResponseEntity<TokenSwapManageResponse> response = restTemplate.exchange(tokenSwapManageCheckTokenUrl, method, formEntity, TokenSwapManageResponse.class);
        log.info("验证token结果:{}", JSON.toJSONString(response));
        TokenSwapManageResponse body = response.getBody();
        if (null != body) {
            String rtnCode = body.getCode();
            if ("0".equals(rtnCode)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 构造http请求的头部信息
     *
     * @return http头部信息
     */
    private HttpHeaders getJsonHeader() {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add(ACCEPT, MediaType.APPLICATION_JSON.toString());
        return headers;
    }

}
